package com.robot.interceptor;


import com.robot.model.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 * User: li
 * Date: 2019/6/23
 * Time: 14:42
 * PROJECT：robot
 * PACKAGE: com.robot
 *
 * @author:55324936@qq.com To change this template use File | Settings | File Templates.
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        User User = (User) request.getSession().getAttribute("user");
        if(null ==User){
            //通过获取消息头里面的X-Requested-With 这个属性，如果他等于XMLHttpRequest，认为这是ajax请求
            String x = request.getHeader("X-Requested-With");
            if(!StringUtils.isEmpty(x) && x.equalsIgnoreCase("XMLHttpRequest")){
                /**要告诉前端的ajax你要做出重定向的操作**/
                response.setHeader("REDIRECT","REDIRECT");
                /**告诉他重定向的路径**/
                response.setHeader("PATH","/login/loginPage");
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            }else {
            //说明你没有登录，因为我们的user是在登录之后放入到当前的session里面的
            response.setStatus(HttpServletResponse.SC_FOUND);
            response.sendRedirect("/login/loginPage");
            return false;
            }
        }
        //session去判断你有没有登录
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
